// pages/carts/carts.js
const user = require("../../models/user");
const cart = require("../../models/cart");
const paid = require("../../models/paid");
Page({
  data: {
    value:[]
  },
  onLoad: async function (options) {
    var id = wx.getStorageSync('id');
    if(id){
      var data = await user(id);
      this.setData({
        value:data.data.res[0].cart
      })
    }else{
      wx.navigateTo({
        url: '../login/login'
      })
    }
  },
  async onShow(){
    var id = wx.getStorageSync('id');
    if(id){
      var data = await user(id);
      this.setData({
        value:data.data.res[0].cart
      })
    }else{
      this.setData({
        value:[]
      })
    }
  },
  // 单个商品的进步器 
  onStep(event){
    this.data.value.forEach(res=>{
      if(event.currentTarget.dataset.id==res._id){
        res.num = event.detail;
      }
    });
    this.setData({
      value:this.data.value
    })
  },
  // 商品前面的单个复选框
  onChange(event){
    this.data.value.forEach(res=>{
      if(event.currentTarget.dataset.id==res._id){  
        res.isSelected = event.detail;
      }
    });
    this.setData({
      value:this.data.value
    })
  },
  // 全选
  onChangeAll(event){
    this.data.value.forEach(res=>{  
        res.isSelected = event.detail;
    });
    this.setData({
      value:this.data.value
    })
  },
  // 点击滑块的删除按键
  async onClose(event) {
    var userID = wx.getStorageSync('id');
    var shoeID = event.currentTarget.dataset.id;
    const { position, instance } = event.detail;
    switch (position) {
      case 'left':
      case 'cell':
        instance.close();
        break;
      case 'right':
        instance.close();
        var data = await cart(userID,shoeID,false);
        this.setData({
          value:data.data.res[0].cart
        })
        break;
    }
  },
  // 点击提交按钮
  async onClickButton(){
    this.data.value.forEach(async res=>{  
      if(res.isSelected){
        var strongID = wx.getStorageSync('id');
        let data = await paid(strongID, res._id, true, res.size, res.num);
        let value = await cart(strongID,res._id,false);
        this.setData({
          value:value.data.res[0].cart
        })
        wx.showToast({
          title: data.data.msg,
          icon: 'none'
        });
      }
  });
  }
})